<?php

namespace app\merchants\services;

use app\common\loader\ModelMerchant;
use app\common\loader\ModelShop;
use app\common\loader\Services as CommonServices;
use app\merchants\loader\Model;
use app\merchants\loader\Services;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Db;

/**
 * 店铺商品库存信息
 */
class ShopStockService
{


    /**
     * 店铺商品库存列表
     * @param $where
     * @param $page |数码
     * @param $count |数量
     * @return mixed
     * @throws DbException
     */
    public function page($where, $page, $count)
    {
        $pageList = Model::ShopStock()->shopStockPage($where, $page, $count);
        CommonServices::Helper()->showListTitle($pageList['data'], ['shop' => 'shop_id', 'product_class' => 'class_id']);
        return $pageList;
    }



    /**
     * 店铺商品详情库存列表
     * @param $where
     * @param $page |数码
     * @param $count |数量
     * @return mixed
     * @throws DbException
     */
    public function shopPage($where, $mer_id, $shop_id,$warn_flag, $page, $count)
    {
        $pageList = Model::ShopStock()->shopPage($where, $page, $count);
        $pageList['stock_deficiency'] = $pageList['total_count'];
        if ((int)$warn_flag !== 1) {
            $pageList['stock_deficiency'] = Model::ShopStock()->getStockDeficiency($mer_id,$shop_id);
        }
        CommonServices::Helper()->showListTitle($pageList['data'], ['shop' => 'shop_id', 'product_class' => 'class_id']);
        return $pageList;
    }

    /**
     * 店铺商品库存详情
     * @param $id
     * @return mixed
     */
    public function shopInfo($id)
    {
        $info = Model::ShopStock()->shopInfo($id);
        CommonServices::Helper()->showInfoTitle($info, ['shop' => 'shop_id', 'product_class' => 'class_id']);
        return $info;
    }


    /**
     * 预警状态修改
     */
    public function shopSaveWarn($id, $type): int
    {
        return Model::ShopStock()->shopSaveWarn($id, $type);
    }


    /**
     * 门店库存调拨
     * @param     $id |主键
     * @param     $num | 数量
     * @param     $type | 类型
     * @param     $op_user | 操作人
     * @param int $dest_shop_ip |目标shop
     * @throws DbException
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function shopSaveStock($id, $num, $type, $op_user, int $dest_shop_ip = 0): void
    {
        try {


            $shopStockModel = Model::ShopStock();
            // 判断当前商品的库存是否正确
            $stockInfo = $shopStockModel->where('id', $id)->find();

            if (empty($stockInfo)) {
                throw  new Exception("未找到记录", API_ERROR);
            }
            if ($stockInfo['sum_num'] < $num) {
                throw  new Exception('店铺剩余库存不足', API_ERROR);
            }

            //判断目标店铺是否存在
            if ((int)$type === 2) {
                if ((int)$stockInfo['shop_id'] === $dest_shop_ip) {
                    throw  new Exception('源店铺和目标店铺不能是同一个', API_ERROR);
                }
                if (ModelShop::Shop()->where('id', $dest_shop_ip)->where('mer_id', $stockInfo['mer_id'])->count() < 1) {
                    throw  new Exception('目标店铺不存在', API_ERROR);
                }
            }
            Db::startTrans();
            //回收店铺库存
            $shopStockModel->recycleShopVirtualStock($stockInfo['shop_id'], $stockInfo['product_code'], $num, $op_user);

            //目标店铺增加下单操作
            // 将库存转移到目录店铺下
            if ((int)$type === 2) {
                //重新走下单流程
                $orderData = [
                    'shop_id' => $dest_shop_ip,
                    'memo' => '库存转移',
                    'op_user' => $op_user,
                    'mer_id' => $stockInfo['mer_id'],
                    'data' => [[
                        "product_code" => $stockInfo['product_code'],
                        "num" => $num
                    ]]
                ];
                Services::Order()->orderAdd($orderData, $num, $op_user, $stockInfo['mer_id'], true);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }

    }

    /**
     * 商品库存
     * @param string $merid 商户编号
     * @param $where
     * @param $page
     * @param $page_size
     * @return mixed
     * @throws DbException
     */
    public function shopProductStock(string $mer_id, $where, $page, $page_size)
    {
        $list = Model::ShopStock()->shopProductStock($mer_id, $where, $page, $page_size);

        if (!empty($list['data'])) {
            $product_code = array_column($list['data'], 'product_code');

            $codeTitle = ModelMerchant::Product()->getProductAndClassTitle($mer_id, $product_code);

            foreach ($list['data'] as &$row) {
                if (isset($codeTitle[$row['product_code']])) {
                    $row = array_merge($row, $codeTitle[$row['product_code']]);
                } else {
                    $row = array_merge($row, ['title' => '未知', 'sub_title' => '', 'class_title' => '']);
                }
            }
        }
        return $list;
    }


}
